<template>
  <div class="page shake">
    <h4>手机摇一摇的功能</h4>
    <h4>摇动次数：{{this.count}}</h4>
    <!-- 摇一摇音效 -->
    <audio
      src="https://syruptech.cn/vue-test/static/audio/shake.mp3"
      ref="shakeAudio"
    >
      您的浏览器不支持 audio 标签。
    </audio>
    <van-button
      class="default"
      @click="backHome"
      type="primary"
    >返回首页</van-button>
  </div>
</template>

<script>
import util from './../util/index'
import Shake from 'shake.js'

export default {
  name: 'shake',
  data () {
    return {
      count: 0
    }
  },
  mounted () {
    this.shakeTips();
    // 实例化一个 shake 对象
    let myShakeEvent = new Shake({
      threshold: 15, // 默认摇动阈值
      timeout: 1000 // 默认两次事件间隔时间
    })
    // 监听设备的动作
    myShakeEvent.start();
    // 添加一个事件监听
    window.addEventListener('shake', this.shakeEventDidOccur, false);
  },
  created () {
  },
  computed: {
  },
  activated () {
    this.count = 0;
    this.shakeTips();
  },
  methods: {
    // 摇动的回调函数
    shakeEventDidOccur () {
      // 获取音频标签
      let audio = this.$refs.shakeAudio;
      if (window.navigator.vibrate) {
        navigator.vibrate(500);
      }
      // 播放音频
      audio.play();
      this.count++;
      this.$toast('摇动了' + this.count + '次！');
    },
    shakeTips () {
      let url = window.location.href;
      let HTTP = url.split(':')[0];
      if (util.terminal() == -1) {
        this.$toast('PC端不支持摇一摇功能！');
      }
      if (util.terminal() == 1) {
        if (HTTP != 'https') {
          this.$toast('IOS手机需要https协议支持摇一摇功能！');
        }
      }
    },
    backHome () {
      this.$router.replace({ name: 'home' });
    }
  },
  components: {
  }
}
</script>

<style lang="less" scoped>
h4 {
  display: inline-block;
  width: 100%;
  font-size: 0.36rem;
}
.default {
  position: absolute;
  bottom: 5%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

